﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Web.DynamicData;
using System.Data.SqlClient;

namespace salarioprofessoresInsert
{
    public partial class Insert : System.Web.UI.Page
    {
        protected MetaTable table;

        protected void Page_Init(object sender, EventArgs e)
        {
            DynamicDataManager1.RegisterControl(DetailsView1);
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            table = DetailsDataSource.GetTable();
            Title = table.DisplayName;            
        }

        protected void DetailsView1_ItemCommand(object sender, DetailsViewCommandEventArgs e)
        {
            if (e.CommandName == DataControlCommands.CancelCommandName)
            {
                Response.Redirect("List.aspx?codigoProfessor=" + Request["codigoProfessor"]);
                //Response.Redirect(table.ListActionPath);
            }
        }

        protected void DetailsView1_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
        {
            if (e.Exception == null || e.ExceptionHandled)
            {
                System.Data.SqlClient.SqlConnection sqlc = new System.Data.SqlClient.SqlConnection(ConfigurationManager.AppSettings["baseDados"]);
                sqlc.Open();

                System.Data.SqlClient.SqlConnection sqld = new System.Data.SqlClient.SqlConnection(ConfigurationManager.AppSettings["baseDados"]);
                sqld.Open();

                string sqlMax = "SELECT MAX(codigoSalarioProfessor) AS codigoSalarioProfessor FROM salarioProfessor";

                System.Data.SqlClient.SqlCommand cmdPegar = new System.Data.SqlClient.SqlCommand(sqlMax, sqlc);
                System.Data.SqlClient.SqlDataReader drPegar = cmdPegar.ExecuteReader();
                drPegar.Read();

                string codigoSalarioProfessorMax = drPegar["codigoSalarioProfessor"].ToString();

                cmdPegar.Dispose();
                drPegar.Close();

                string sqlDatas = "SELECT * FROM salarioProfessor where codigoSalarioProfessor = " + codigoSalarioProfessorMax;

                System.Data.SqlClient.SqlCommand cmdPegarDatas = new System.Data.SqlClient.SqlCommand(sqlDatas, sqlc);
                System.Data.SqlClient.SqlDataReader drPegarDatas = cmdPegarDatas.ExecuteReader();
                drPegarDatas.Read();

                string dataFinal = drPegarDatas["dataFinal"].ToString();
                string dataInicial = drPegarDatas["dataInicial"].ToString();
                string ValorSalario = drPegarDatas["ValorSalario"].ToString();

                cmdPegarDatas.Dispose();
                drPegarDatas.Close();

                string sqlVerificarData = "SELECT codigoSalarioProfessor, dataInicial, dataFinal, codigoProfessor, ValorSalario ";
                sqlVerificarData = sqlVerificarData + "FROM salarioProfessor WHERE codigoProfessor = " + Request["codigoProfessor"];

                System.Data.SqlClient.SqlCommand cmdPegarVerificarData = new System.Data.SqlClient.SqlCommand(sqlVerificarData, sqlc);
                System.Data.SqlClient.SqlDataReader drPegarVerificarData = cmdPegarVerificarData.ExecuteReader();

                if (drPegarVerificarData.HasRows)
                {
                    while (drPegarVerificarData.Read())
                    {
                        string datasIniciais = drPegarVerificarData["dataInicial"].ToString();
                        string datasFinais = drPegarVerificarData["dataFinal"].ToString();

                        if (Convert.ToDateTime(dataInicial) >= Convert.ToDateTime(datasIniciais) && Convert.ToDateTime(dataInicial) <= Convert.ToDateTime(datasFinais))
                        {
                            string sqlDelDet = "delete from salarioProfessor where codigoSalarioProfessor = " + codigoSalarioProfessorMax;

                            System.Data.SqlClient.SqlCommand del = new System.Data.SqlClient.SqlCommand(sqlDelDet, sqld);
                            del.ExecuteNonQuery();
                            del.Dispose();

                            Response.Redirect("Insert.aspx?codigoProfessor=" + Request["codigoProfessor"] + "&erro=jaExiste");
                        }

                        if (Convert.ToDateTime(dataFinal) >= Convert.ToDateTime(datasIniciais) && Convert.ToDateTime(dataFinal) <= Convert.ToDateTime(datasFinais))
                        {
                            string sqlDelDet = "delete from salarioProfessor where codigoSalarioProfessor = " + codigoSalarioProfessorMax;

                            System.Data.SqlClient.SqlCommand del = new System.Data.SqlClient.SqlCommand(sqlDelDet, sqld);
                            del.ExecuteNonQuery();
                            del.Dispose();

                            Response.Redirect("Insert.aspx?codigoProfessor=" + Request["codigoProfessor"] + "&erro=jaExiste");
                        }
                    }
                }

                cmdPegarVerificarData.Dispose();
                drPegarVerificarData.Close();

                DateTime Hoje = DateTime.Now;
                string dataAtual = Hoje.ToString("dd/MM/yyyy");

                if (dataFinal == "")
                {
                    dataFinal = dataAtual;
                }

                TimeSpan dif = Convert.ToDateTime(dataFinal).Subtract(Convert.ToDateTime(dataInicial));

                if (dif.Days > 0)
                {
                    string q = "update salarioProfessor set codigoProfessor=" + Request["codigoProfessor"].ToString() + " where codigoSalarioProfessor = " + codigoSalarioProfessorMax;

                    SqlCommand alterar = new SqlCommand(q, sqlc);
                    alterar.ExecuteNonQuery();
                    alterar.Dispose();

                    string data = DateTime.Now.ToString("dd/MM/yyyy");
                    string hora = DateTime.Now.ToString("HH:mm");

                    //string insertLogAcao = "insert into logAcao (codigoUsuario, dataLogAcao, horaLogAcao, tipoLogAcao, tipoTabelaLogAcao, descricaoLogAcao) ";
                    //insertLogAcao = insertLogAcao + "values (" + Session["codigoUsuario"].ToString() + ", '" + data + "', '" + hora + "', 'Cadastro', 'Tarífas', ";
                    //insertLogAcao = insertLogAcao + "'Código: " + codigoSalarioProfessorMax + ", Código do trajeto: " + Request["codigoTrajeto"].ToString() + ", ";
                    //insertLogAcao = insertLogAcao + "Data inicial: " + dataInicial + ", Data Final: " + dataFinal + ", Valor da tarifa: " + valorTarifaTrajeto + "')";

                    System.Data.SqlClient.SqlConnection sqly = new System.Data.SqlClient.SqlConnection(ConfigurationManager.AppSettings["baseDados"]);
                    sqly.Open();
                    //System.Data.SqlClient.SqlCommand inserirviagem = new System.Data.SqlClient.SqlCommand(insertLogAcao, sqly);
                    //inserirviagem.ExecuteNonQuery();
                    //inserirviagem.Dispose();
                    sqly.Close();

                    Response.Redirect("List.aspx?codigoProfessor=" + Request["codigoProfessor"]);
                }
                else
                {
                    string sqlDelDet = "delete from salarioProfessor where codigoSalarioProfessor = " + codigoSalarioProfessorMax;

                    System.Data.SqlClient.SqlCommand del = new System.Data.SqlClient.SqlCommand(sqlDelDet, sqlc);
                    del.ExecuteNonQuery();
                    del.Dispose();

                    Response.Redirect("Insert.aspx?codigoProfessor=" + Request["codigoProfessor"] + "&erro=dataMenor");
                }

                sqlc.Close();
                sqld.Close();
            }
        }
    }
}
